package org.elsfs.auth.client;

import static org.assertj.core.api.Assertions.assertThat;

import org.elsfs.auth.entity.ResponseBody;
import org.elsfs.framework.generator.SnowFlake;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

class CLIENT_SECRET_POST extends AbstractClientTypeAuthorizationServerTests {
  String CLIENT_ID = "test_client_secret_post";
  String CLIENT_SECRET = "secret";

  @Test
  @Order(40)
  @Override
  void exchange() {
    //    addRegisteredClient();
    MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
    requestMap.add(OAuth2ParameterNames.CLIENT_ID, CLIENT_ID);
    requestMap.add(OAuth2ParameterNames.SCOPE, "openid profile");
    requestMap.add(OAuth2ParameterNames.GRANT_TYPE, "client_credentials");
    requestMap.add(OAuth2ParameterNames.CLIENT_SECRET, CLIENT_SECRET);
    RequestEntity<MultiValueMap<String, Object>> request =
        RequestEntity.post(getUri())
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .accept(MediaType.APPLICATION_JSON)
            .body(requestMap);
    // 3.响应体
    ResponseEntity<ResponseBody> exchange = restTemplate.exchange(request, ResponseBody.class);
    ResponseBody body = exchange.getBody();
    LOGGER.info("{}", body);
    assertThat(body).isNotNull();
  }

  protected String getUri() {
    return new StringBuffer("http://localhost:")
        .append(this.environment.getProperty("local.server.port", "8080"))
        .append(PATH)
        .toString();
  }

  /** 添加测试注册客户端 */
  private void addRegisteredClient() {
    RegisteredClient registeredClient =
        RegisteredClient.withId(new SnowFlake(31).nextId() + "")
            .clientId(CLIENT_ID)
            .clientSecret(passwordEncoder.encode(CLIENT_SECRET))
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .scope(OidcScopes.OPENID)
            .scope(OidcScopes.PROFILE)
            .build();
    registeredClientRepository.save(registeredClient);
  }
}
